<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>广告滚动框</title>
	<style type="text/css">
		*{margin: 0;padding: 0;}
		#ad{width: 100px;height: 100px;background: #369;border-radius:50%;position:absolute;}
	</style>
</head>
<body>
	<div id="ad"></div>
	<script type="text/javascript" src="jquery-1.8.3.min.js"></script>
	<script type="text/javascript">
	// 全局变量
	var inte = null;//定时器全局变量
	var stepX = 3;//移动步进
	var stepY = 3;//移动步进
	var i = 1;

	//封装函数 自动运行
	autoRun();

	var arr = ['国','庆','快','乐'];

	$('#ad').css({textAlign:'center',lineHeight:'100px',fontSize:'50px',color:'red'});
	$('#ad').html(arr[0])

	var init = setInterval(function(){
		$('#ad').html(arr[i]);
		i++;
		if(i == arr.length){
			i=0;
		}
	},1000);

	function autoRun(){
		//启动定时器
		inte = setInterval(function(){
			//获取当期元素相对于父级元素的偏移量
			var _l = $('#ad').position().left;
			var _t = $('#ad').position().top;
			//计算新的left top
			var newLeft = _l + stepX;
			var newTop = _t + stepY;

			//获取最大值
			var maxLeft = $(window).width() - $('#ad').width();
			var maxTop = $(window).height() - $('#ad').height();
			//检测越界
			if(newLeft >= maxLeft || newLeft <= 0){
				stepX = -stepX;
				//随机颜色
				var r = rand(0,255);
				var g = rand(0,255);
				var b = rand(0,255);
				$('#ad').css('background','rgb('+r+','+g+','+b+')');
			}
			if(newTop >= maxTop || newTop <= 0){
				stepY = -stepY;
				//随机颜色
				var r = rand(0,255);
				var g = rand(0,255);
				var b = rand(0,255);
				$('#ad').css('background','rgb('+r+','+g+','+b+')');
			}

			//设置样式
			$('#ad').css({left:newLeft+'px',top:newTop+'px'});
		},10);
	}

	//随机函数
	function rand(m,n){
		return Math.floor(Math.random()*(n-m+1))+m;
	}

	</script>
</body>
</html>